# map mgr
from Cube.map import MapMgrGet
# event listener
from direct.showbase import DirectObject
# cmd event
from Cube.command.QCmdInputPipe.EventDefine import event_CMDPIPE_SYNCFAIL
from Cube.command.QCommand.EventDefine import event_QCMD_GAMEINITIALIZEDONE, \
                                              event_QCMD_GAMERUN, event_QCMD_GAMEPAUSE
from EventDefine import event_GAMECONTROL_INITIALIZEDONE, event_GAMECONTROL_DESTROY
# cmd
from Cube.command.QCommand import QCmdGameInitializeDone
# ObjectPool
from Cube.game.QObjectBase import QObjectBase


class Controller(DirectObject.DirectObject):
    def __init__(self):
        # cmdpipe
        self.accept(event_CMDPIPE_SYNCFAIL, self._CmdSyncFailhandle)
        # cmd
        self.accept(event_GAMECONTROL_INITIALIZEDONE, self._InitializeDoneAck)
        self.accept(event_QCMD_GAMEINITIALIZEDONE, self._InitializeDoneReply)
        self.accept(event_QCMD_GAMERUN, self._run)
        self.accept(event_QCMD_GAMEPAUSE, self._pause)
        #self.accept(event_GAMECONTROL_DESTROY, self.destroy)

    def Initial(self):
        self._MapBodyLoad()   # assign self.MapBody
        self.State = "pause"  # "run" , "pause"
        self.MapBody.Initialize()

    def _MapBodyLoad(self):
        mapMgr = MapMgrGet()
        MapBody = mapMgr.CurrentMapBody
        if MapBody is None:
            self.MapBody = mapMgr.MapBodyLoad()
        else:
            self.MapBody = MapBody

    def _InitializeDoneAck(self):
        QCmdGameInitializeDone().Send()

    # override it
    def _InitializeDoneReply(self, memberID):
        pass

    def _CmdSyncFailhandle(self):
        # TODO: resume?
        print "MapBodyController._CmdSyncFailhandle"
        #self._pause()

    def _run(self, memberID):
        if self.State == "pause":
            self.MapBody.run()

    def _pause(self, memberID):
        if self.State == "run":
            self.MapBody.pause()

    def destroy(self):
        # called by QMapMgrFSM.exitTheme
        self.ignoreAll()
        self.MapBody.destroy()
        # check the ObjectPool
        print QObjectBase.ObjectPool